<?php
namespace app\common\controller;
use app\common\model\Goods;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;

class Tools
{
	// 上传图像
	// public function upload_img($imgName, $who, $thumb=[])
	// {
	// 	$id = session('merchant')['merchant_id'];
	// 	$file = request()->file('Filedata');
	// 	$filename = $imgName . '_'.$who.'_'. $id;
	// 	$filePath = config($who.'_img_path');
	// 	$info = $file->move($filePath, $filename);
	// 	if($info){
	// 		$ret['images'][0] = $info->getFilename();
	// 		if($thumb)
	// 		{
	// 			foreach($thumb as $k => $v)
	// 			{
				
	// 				$ret['images'][$k+1] = $filePath . DS . $imgName . '_'.$v[0].'_'. $v[1].'_'.$who.'_'. $id . '.' . $info->getExtension();
	// 				$img = $filePath . DS . $info->getFilename();
	// 				// halt($thumbImg);
	// 				$image = \think\Image::open($img);
	// 				$image->thumb($v[0], $v[1], \think\Image::THUMB_FIXED)->save($ret['images'][$k+1]);
	// 			}
	// 		}
	// 	}else{
	// 	// 上传失败获取错误信息
	// 		return returnJson(0, $file->getError());
	// 	}

	// 	return $ret;
	// } 

	// CURD操作
	public function insert($table= '', $data=[], $scene='', $method="")
	{
	   if(request()->$method())
	    {
	          $model = model($table);
	          $validate = $model->intValidate();
	          if(!($validate->scene($scene)->check($data)))
	                return returnJson(0, $validate->getError());
	          if($model->save($data))
	          {
	                return returnJson(1, '添加成功'); 
	          }
	          else
	          {
	              return returnJson(0, '数据添加失败，请稍后重试'); 
	          }   
	    } 
	}


    public function sendMsg($phone)
    {
    	if(empty($phone))
			return returnJson(0, '手机号不能为空！');

		$is_mobile = is_mobile($phone);
		if(!$is_mobile) 
			return returnJson(0, '请输入正确的手机号');

		$charset = '1234567890';
		$code = '';
		$_len = strlen($charset) - 1;
		for ($i=0; $i < 6; $i++) {
			$code .= $charset[mt_rand(0, $_len)];
		}

		$ParamString = "{'webname':'','code':'$code','number':'5'}";
		$RecNum = $phone;
		//$result = sendMessage($ParamString, $RecNum);
		$result = $this->sendMessage($ParamString, $RecNum,"租介","SMS_91850003");
		if($result){
			$tempphone = model('temp_phone');
			$tempphone->phone = $phone;
			$tempphone->ip = getIP();
			$tempphone->code = $code;
			$tempphone->create_time = time();
			$tempphone->deadline = time() + 300;
			if(!$tempphone -> save())
			{
				return false;
			}
		
			return true;
		}else{
			return returnJson(0, '发送失败');
		}
		
		
    }



    public static function upload_img($whereName, $column, $width="", $height="",$b=true)
	{
		// $column = store_face_img_130_130
		// 打开图片的相对路径
		$imgpath = config('img_path');
		$imgRootPath = config('imgRootPath');
		$filename = Goods::makeFileName();
		$type = Goods::upload($whereName, $filename);
		if($type) 
		{
			$savepath = $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type;
			$thumbfile = session('merchant.merchant_id') . '_' . $column . '.' . $type;
			$thumbName = $imgpath  . '/' . $whereName . '/' . $thumbfile;

			$image = \think\Image::open($imgpath . '/'. $whereName .'/' . $filename . '.' . $type);
		//	$image->thumb($width, $height, \think\Image::THUMB_FIXED)->save($thumbName);
			$image->save($thumbName);
			$data = [
				'access_url' => $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type,
				'filename' => $thumbfile,
			];

			return $data;
		}
		
	}

	public static function upload_goods_img($whereName, $width="", $height="")
	{
		// $column = store_face_img_130_130
		// 打开图片的相对路径
		$imgpath = config('img_path');
		// 绝对路径
		$imgRootPath = config('imgRootPath');
		$storeId = Goods::getStoreId();
		$merchantId = session('merchant.merchant_id');
		$old_filename = $storeId . $merchantId . time();
 		$filename = $storeId . $merchantId . time() . mt_rand(1000, 9999);
		$type = Goods::upload($whereName, $old_filename);
		 
		if($type) 
		{
			$savepath = $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type;
			$thumbfile = $filename . '.' . $type;
			$thumbName = $imgpath  . '/' . $whereName . '/' . $thumbfile;

			$image = \think\Image::open($imgpath . '/'. $whereName .'/' . $old_filename . '.' . $type);
			// halt($image);
			$image->save($thumbName);
			//$image->thumb($width, $height, \think\Image::THUMB_FIXED)->save($thumbName);
			// halt($image);
			$data = [
				'access_url' => $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type,
				'filename' => $thumbfile,
			];

			return $data;
		}
		
	}

	/*发送短信方法
   *$ParamString 参数 json格式
   *$RecNum      电话号码
   *$SignName    短信签名
   *$TemplateCode短信模板Code
   * */
	function sendMessage($ParamString, $RecNum, $SignName, $TemplateCode)
	{

		require_once __DIR__.'/../../../vendor/Api/dysms/vendor/autoload.php';    //此处为你放置API的路径
		Config::load();//加载区域结点配置
		//此处需要替换成自己的AK信息
		$accessKeyId = "LTAIDfBca1uxw8bs";//参考本文档步骤2
		$accessKeySecret = "rTDB2VwfPeDdyPnhHqTWCIyqxOG6Kv";//参考本文档步骤2
		//短信API产品名（短信产品名固定，无需修改）
		$product = "Dysmsapi";
		//短信API产品域名（接口地址固定，无需修改）
		$domain = "dysmsapi.aliyuncs.com";
		//暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
		$region = "cn-hangzhou";
		//初始化访问的acsCleint
		$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
		DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
		$acsClient= new DefaultAcsClient($profile);
		$request = new SendSmsRequest;
		//必填-短信接收号码。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		$request->setPhoneNumbers($RecNum);
		//必填-短信签名
		$request->setSignName($SignName);
		//必填-短信模板Code
		$request->setTemplateCode($TemplateCode);
		//选填-假如模板中存在变量需要替换则为必填(JSON格式),友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		$request->setTemplateParam($ParamString);
		//选填-发送短信流水号
		// $request->setOutId("1234");
		//发起访问请求
		return $acsClient->getAcsResponse($request);
	}
	
	/* 输出Excel          方法
	 * $letter            表头(A,B,C....)
	 * $tableheader       表头数组
	 * $data              数据
	 * $excel_name excel  名称
	 */
    public function toExcel($letter,$tableheader,$data,$excel_name)
	{
		require_once __DIR__.'/../../../vendor/phpexcel/Classes/PHPExcel.php'; //此处为你放置API的路径
		$excel=new \PHPExcel();
		//填充表头信息
		for($i = 0;$i < count($tableheader);$i++) {
			$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
			$excel->getActiveSheet()->getColumnDimension($letter[$i])->setWidth('20');
		}
		$datacount=count($data);
		for ($i = 2;$i <= $datacount + 1;$i++)
		{
			$j = 0;
			foreach ($data[$i - 2] as $key=>$value)
			{
				$excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
				$j++;
			}
		}

		//创建Excel输入对象
		$write =  \PHPExcel_IOFactory::createWriter($excel,'Excel2007');
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-execl");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");;
		header('Content-Disposition:attachment;filename="'.$excel_name.'.xls"');
		header("Content-Transfer-Encoding:binary");
		$write->save('php://output');
	}
	
	
	
	
}